// 留言功能的路由

const router = require('koa-router')()
const loginCheck = require('../middleware/loginCheck')
const { create, getList, del, update } = require('../controller/commentWeb')

router.prefix('/comment')

// 更新留言
router.post('/update', loginCheck, async (ctx,) => {
  const { _id, content } = ctx.request.body // 获取 id content
  const { username } = ctx.session.userInfo // 获取用户名
  const responseModel = await update(_id, username, content)
  if (!responseModel.ok) ctx.status = 500
  ctx.body = responseModel
})

// 删除留言
router.post('/del', loginCheck, async (ctx) => {
  const { _id } = ctx.request.body // 获取 id
  const { username } = ctx.session.userInfo // 获取用户名
  const responseModel = await del(_id, username)
  console.log('be del responseModel = \n',responseModel)
  if (!responseModel.ok) ctx.status = 500
  ctx.body = responseModel
})

// 获取留言列表
router.get('/list',loginCheck, async (ctx) => {
  // 获取 filterType: 1-全部  2-自己
  let { filterType } = ctx.query
  filterType = parseInt(filterType) || 1
  let username = filterType === 2 ? ctx.session.userInfo.username : ''// 获取当前用户名
  // 获取留言列表
  const responseModel = await getList(username)
  if (!responseModel.ok) ctx.status = 500
  ctx.body = responseModel
})

// 创建留言
router.post('/create', loginCheck, async (ctx) => {
  // 获取留言信息
  const { content } = ctx.request.body
  const { username } = ctx.session.userInfo
  const responseModel = await create(content, username)
  if (!responseModel.ok) ctx.status = 500
  ctx.body = responseModel
})

module.exports = router
